<template>
  <div>
    <div class="theme-content">
      <div class="theme-content-item padding-20px">
        <div>
          <div style="margin-bottom: 13px">
            <div class="left-title">分佣规则</div>
            <div style="color: #409EFF;margin-top: 20px">当前生效规则</div>
            <div class="param-item">本级返利：{{effectiveRule.data.thisLevelRate}}%</div>
            <div class="param-item">下级返利：{{effectiveRule.data.upOneLevelRate}}%</div>
            <div class="param-item">生效日期：{{effectiveRule.data.effectiveTime}}</div>
            <div style="color: #409EFF;margin-top: 30px">未来生效规则</div>
            <div class="param-item" v-show="isAdd && configFlag === 0">暂无</div>
            <div v-if="configFlag === 0 && !isAdd && waitingRule.data">
              <div class="param-item">本级返利：{{waitingRule.data.thisLevelRate}}%</div>
              <div class="param-item">下级返利：{{waitingRule.data.upOneLevelRate}}%</div>
              <div class="param-item">生效日期：{{waitingRule.data.effectiveTime}}</div>
            </div>

            <el-form v-if="configFlag === 1" ref="commissionRuleAddRef" :model="commissionRuleAddRequest.data" :rules="rules" >
              <el-form-item class="param-item" label="本级返利" prop="thisLevelRate">
                <el-input v-model="commissionRuleAddRequest.data.thisLevelRate" placeholder="请填写本级返利"
                          @input="commissionRuleAddRequest.data.thisLevelRate = limitInput(commissionRuleAddRequest.data, 'thisLevelRate', 'upOneLevelRate')"/>
                <span style="margin-left: 5px">%</span>
              </el-form-item>
              <el-form-item class="param-item" label="下级返利" prop="upOneLevelRate">
                <el-input v-model="commissionRuleAddRequest.data.upOneLevelRate" placeholder="请填写下级返利"
                          @input="commissionRuleAddRequest.data.upOneLevelRate = limitInput(commissionRuleAddRequest.data, 'upOneLevelRate', 'thisLevelRate')"/>
                <span style="margin-left: 5px">%</span>
              </el-form-item>
              <el-form-item class="param-item" label="生效日期" prop="immediateFlag">
                <el-radio v-model="commissionRuleAddRequest.data.immediateFlag" label="1">立即生效</el-radio>
                <el-radio v-model="commissionRuleAddRequest.data.immediateFlag" label="0">
                  <el-form-item prop="effectiveTime">
                    <el-date-picker v-model="commissionRuleAddRequest.data.effectiveTime" type="date" placeholder="请选择生效日期" format="YYYY/MM/DD"
                                    value-format="YYYY-MM-DD HH:mm:ss" :disabled="commissionRuleAddRequest.data.immediateFlag !== '0'"
                                    :disabled-date="disabledDate"/>
                  </el-form-item>
                </el-radio>
              </el-form-item>
            </el-form>
            <div>
              <el-button v-hasPermi="[$button.confcommissionRateedit || null]"
                         v-if="configFlag === 0" type="primary" class="param-button" @click="addOrEditHandle(isAdd)">{{isAdd? '新增' : '修改'}}</el-button>
              <el-button v-hasPermi="[$button.confcommissionRateremove || null]"
                         v-if="configFlag === 0 && !isAdd" type="danger" class="param-button" @click="delHandle">删除</el-button>
              <el-button v-if="configFlag === 1" type="primary" class="param-button" @click="updateHandle">保存</el-button>
              <el-button v-if="configFlag === 1" class="param-button" @click="closeHandle" >取消</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {commissionConfDetailApi, commissionConfDelApi, commissionConfUpdateApi} from './const'
import { IntegerPoint } from '@/utils/checkInput'
import $button from '@/button'
const { proxy } = getCurrentInstance();
const rules = reactive({
  thisLevelRate: [
    { required: true, message: '请填写本级返利', trigger: 'blur' },
  ],
  upOneLevelRate: [
    { required: true, message: '请填写下级返利', trigger: 'blur' },
  ],
  // effectiveTime: [
  //   { required: true, message: '请选择生效日期', trigger: 'blur' },
  // ],
  immediateFlag: [
    { required: true, message: '请选择生效日期', trigger: 'blur' },
  ],
})
const effectiveRule = reactive({ data: {} })
const waitingRule = reactive({ data: {} })
const commissionRuleAddRequest = reactive({ data: {} })
const isAdd = ref(true)
const configFlag = ref(0)
//限制只能选择未来时间
const disabledDate = (time) => {
  return time < new Date()
}

const getCommissionDetail = () => {
  commissionConfDetailApi().then(res => {
    effectiveRule.data = res.data.effective
    waitingRule.data = res.data.waiting
    isAdd.value = !waitingRule.data
    console.log(res, effectiveRule.data, waitingRule.data);
  })
}
const updateHandle = () => {
  proxy.$refs["commissionRuleAddRef"].validate(valid => {
    if (valid) {
      commissionConfUpdateApi(commissionRuleAddRequest.data).then(res => {
        ElMessage.success(res.msg || '操作成功')
        isAdd.vuale = false
        closeHandle()
        getCommissionDetail()
      })
    }
  })
}
const delHandle = () => {
  let text = '确定删除该数据吗？'
  proxy.$modal.confirm(text).then(() => {
    commissionConfDelApi().then(res => {
      ElMessage.success(res.msg || '操作成功')
      isAdd.vuale = true
      closeHandle()
      getCommissionDetail()
    })
  })
}
const addOrEditHandle = (isAdd) => {
  configFlag.value = 1
  if(!isAdd) {
    Object.keys(commissionRuleAddRequest).forEach((key) => { commissionRuleAddRequest[`${key}`] = waitingRule[`${key}`] })
    commissionRuleAddRequest.data.immediateFlag = waitingRule.data.effectiveTime? '0' : '1'
  }
}
const closeHandle = () => {
  configFlag.value = 0
  commissionRuleAddRequest.data = {}
}
//输入限制，正数且两者相加最大不能超过100，支持1位小数
function limitInput(sub, nowPercent, another) {
  let result = IntegerPoint(sub[nowPercent])
  if (result == NaN || result == '') {
    return ''
  }
  if(sub[another] === undefined || (100 - Number(sub[another]) >= result)) {
    return result
  } else {
    return 100 - Number(sub[another])
  }
}

onMounted(() => {
  // getCommissionDetail()
})

watch(
  configFlag,
  (newValue, oldValue) => {
    if (newValue == 0) {
      getCommissionDetail();
    }
  },
  { immediate:true }
)

</script>
<style>
.param-item {
  margin-top: 14px;
  font-size: 14px;
}
.param-button {
  margin-top: 20px;
}

</style>
